﻿using System;
using System.Reflection;

namespace PocketBook.Model
{
    [AttributeUsageAttribute(AttributeTargets.Class)]
    public class DesignResourcesAttribute : Attribute
    {
        private readonly Type _resourceType;

        public DesignResourcesAttribute(Type resourceType)
        {
            _resourceType = resourceType;
        }

        public T FindResource<T>(object source)
        {
            // ReSharper disable PossibleNullReferenceException
            var typeName = source.GetType().FullName;
            return FindResource<T>(typeName.Substring(typeName.LastIndexOf('.') + 1));
// ReSharper restore PossibleNullReferenceException
        }

        public T FindResource<T>(string resourceName)
        {
            var property = _resourceType.GetProperty(resourceName, BindingFlags.NonPublic | BindingFlags.Static);

            if (property == null) throw new InvalidOperationException(string.Format("Resource Type {0} does not have the property '{1}'", _resourceType, resourceName));
            if (property.PropertyType != typeof(T)) throw new InvalidOperationException(string.Format("Resource Type {0} does not have the property '{1}'", _resourceType, resourceName));

            return (T) property.GetValue(property.DeclaringType, null);
        }
    }
}